package com.c.ctgproject.ui.storage.material

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.c.ctgproject.base.BaseViewModel
import com.c.ctgproject.http.ApiMethods
import com.c.ctgproject.utils.awaitSync
import com.c.ctgproject.utils.launch
import com.c.ctgproject.utils.userToken
import com.google.gson.Gson
import okhttp3.MediaType
import okhttp3.RequestBody

class StorageMaterialInViewModel : BaseViewModel() {
    private val mDetail = MutableLiveData<String>()
    val detail: LiveData<String> get() = mDetail

    private val mConfirmResult = MutableLiveData<String>()
    val confirmResult: LiveData<String> get() = mConfirmResult

    private val mCancelResult = MutableLiveData<String>()
    val cancelResult: LiveData<String> get() = mCancelResult
    fun getList(page: Int, size: Int) {
        launch({
            mDetail.value =
                ApiMethods.getApiService().getStorageMaterial(userToken, page, size).awaitSync()
        }, {
            mError.value = it.message.toString()
        })
    }

    fun confirm(isIn: Int, materialInNo: String, inWeight: Double = 0.0, materialId: Int = 0, inNum: Int = 0) {
        launch {
            val map: MutableMap<String, Any> =
                java.util.HashMap()
            if (inNum != 0) {
                map["inNum"] = inNum
            }
            if (isIn != 0) {
                map["isIn"] = isIn
            }
            map["materialInNo"] = materialInNo
            if (inWeight != 0.0) {
                map["inWeight"] = inWeight
            }
            if (materialId != 0) {
                map["materialId"] = materialId
            }
            val obj = Gson().toJson(map)
            val body = RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"),
                obj
            )
            mConfirmResult.value = ApiMethods.getApiService().storageMaterialInConfirm(
                userToken,
                body
            ).awaitSync()
        }
    }

    fun cancel(materialInNo: String) {
        launch {
            mCancelResult.value = ApiMethods.getApiService().materialInCancel(userToken, materialInNo, "2").awaitSync()
        }
    }


}